package com.efounder.news.fragment;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.mobilenews.R;
import com.efounder.model.RefreshViewEvent;
import com.efounder.news.adapter.ListFragmentAdapter;
import com.efounder.news.bean.ChannelListBean;
import com.efounder.news.bean.MultiLangChannelListBean;
import com.efounder.news.http.NewsRequestManager;
import com.efounder.news.view.LoadingPage;
import com.efounder.service.Registry;
import com.efounder.utils.JfResourceUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class NewsFragment extends BaseFragment {

    private static final String TAG = "NewsFragment";

    private View mView;

    private TabLayout mNewsTabLayout;
    private ViewPager mNewsViewPager;
    private LoadingPage mLoadingPage;
    private View mLineView;

    private ListFragmentAdapter mFragmentAdapter;
    private NewsListFragment mNewsListFragment;

    //新闻类别集合
    private List<MultiLangChannelListBean> mChannelList;
//    private List<NewsListFragment> mNewsListFragments;
    private StubObject stubObject;
    //最新上的角标
    private BadgeView badgeView;

    public NewsFragment() {
        super();
    }

//    @SuppressLint("ValidFragment")
//    public NewsFragment(StubObject object) {
////        Log.e(TAG, "" + object);
//        this.stubObject = object;
//    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mView = inflater.inflate(R.layout.fragment_news, container, false);

        stubObject = (StubObject) getArguments().getSerializable("stubObject");

        mNewsTabLayout = (TabLayout) mView.findViewById(R.id.news_tablayout);
        mNewsViewPager = (ViewPager) mView.findViewById(R.id.news_viewpager);
        mLoadingPage = (LoadingPage) mView.findViewById(R.id.news_load_page);
        mLineView = mView.findViewById(R.id.view_news_line);
        EventBus.getDefault().register(this);

        return mView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //mNewsListFragments = new ArrayList<>();


        mChannelList = new ArrayList<>();
        if (mChannelList.size() == 0) {
            createTestData();
        }
        showTabPage();
        //初始化最新的角标
        initBadge();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        NewsRequestManager.getInstance(getActivity()).cannelOkHttpRequest(TAG);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        //如果点击的是资讯，发送角标隐藏通知
//        if(isVisibleToUser&&EnvironmentVariable.getProperty("news_new_message_notify","0").equals("1")){
//            EnvironmentVariable.setProperty("news_new_message_notify","0");
//            EventBus.getDefault().post(new UpdateBadgeViewEvent(BadgeUtil.CHAT_ID_NEWS+"", (byte) 2));
//        }
    }

    /**
     * 请求服务器的数据
     */
    private void requetServer() {
        showLoadingPage();
        Map<String, String> map = new HashMap<>();

        NewsRequestManager.getInstance(getActivity()).requestAsyn(TAG,"channels", 0, (HashMap<String, String>) map,
                new NewsRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        Gson gson = new Gson();
                        if (result == null || "".equals(result)) {
                            return;
                        }
                        mChannelList = gson.fromJson(result, new TypeToken<List<ChannelListBean>>() {
                        }.getType());
                        if (mChannelList != null) {
                            if (mChannelList.size() == 0) {
                                createTestData();
                            }

                            showTabPage();
                        }


                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
//                            Toast.makeText(getActivity(), errorMsg, Toast.LENGTH_SHORT).show();


                        showErroPage();
                    }
                });
    }

    private void createTestData() {
        createTabFromLocalXml();
        if (mChannelList.size() > 0) {
            return;
        }
        //配置文件没有，初始化 stringarray 中的
        String[] arrayID = getResources().getStringArray(R.array.news_channelid);
        String[] arrayName = getResources().getStringArray(R.array.news_channel_name);
        String[] arrayEnID = getResources().getStringArray(R.array.en_news_channelid);
        String[] arrayEnName = getResources().getStringArray(R.array.en_news_channel_name);
        for (int i = 0; i < arrayID.length; i++) {
            MultiLangChannelListBean multiLangChannelListBean = new MultiLangChannelListBean();
            multiLangChannelListBean.setChannelId(arrayID[i]);
            multiLangChannelListBean.setChannelName(arrayName[i]);
            multiLangChannelListBean.setEnChannelId(i >= arrayEnID.length ? "" : arrayEnID[i]);
            multiLangChannelListBean.setEnChannelName(i >= arrayEnID.length ? "" : arrayEnName[i]);
            mChannelList.add(multiLangChannelListBean);
        }
    }

    private void createTabFromLocalXml() {
        mChannelList.clear();
        //初始化配置文件的菜单
        if (stubObject != null) {
            List<StubObject> subMenus = Registry.getRegEntryList((String) stubObject.getID());
            if (subMenus != null && subMenus.size() > 0) {
                for (int i = 0; i < subMenus.size(); i++) {
                    MultiLangChannelListBean multiLangChannelListBean = new MultiLangChannelListBean();
                    multiLangChannelListBean.setChannelId(subMenus.get(i).getString("channelId", ""));
                    multiLangChannelListBean.setChannelName(subMenus.get(i).getString("caption", ""));
                    multiLangChannelListBean.setEnChannelId(subMenus.get(i).getString("enChannelId", ""));
                    multiLangChannelListBean.setEnChannelName(subMenus.get(i).getString("enCaption", ""));
                    mChannelList.add(multiLangChannelListBean);
                }
                return;
            }
        }
    }

    private void showTabPage() {
//        mNewsListFragments.clear();
//        for (ChannelListBean channel : mChannelList) {
//            mNewsListFragment = NewsListFragment.newInstance(channel.getChannel_id());
//            mNewsListFragments.add(mNewsListFragment);
//        }
        showListPage();
        mFragmentAdapter = new ListFragmentAdapter(getChildFragmentManager(), mChannelList);
        mNewsViewPager.setAdapter(mFragmentAdapter);
        mNewsTabLayout.setupWithViewPager(mNewsViewPager);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshEvent(RefreshViewEvent event){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isAdded()){
                    createTestData();
                    showTabPage();
                }

            }
        },100);

    }
    /**
     * 展示加载页面
     */
    private void showLoadingPage() {
        mLoadingPage.setLoadingView();
        mLineView.setVisibility(View.INVISIBLE);
    }

    /**
     * 展示数据页面
     */
    private void showListPage() {
        mLoadingPage.setSuccessView();
        mLineView.setVisibility(View.VISIBLE);
    }

    /**
     * 显示加载错误的页面
     */
    private void showErroPage() {
        mLoadingPage.setErrorView();
        mLineView.setVisibility(View.INVISIBLE);
        mLoadingPage.setLoadingClickListener(new LoadingPage.LoadingClickListener() {
            @Override
            public void clickListener() {
                requetServer();
            }
        });
    }

    /**
     * 初始化 最新栏目的 角标
     */
    private void initBadge(){
        TextView textView = (TextView)((LinearLayout)((LinearLayout)mNewsTabLayout.getChildAt(0)).getChildAt(0)).getChildAt(1);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) textView.getLayoutParams();
        layoutParams.width = LinearLayout.LayoutParams.MATCH_PARENT;
        layoutParams.height = LinearLayout.LayoutParams.MATCH_PARENT;
        badgeView = new BadgeView(getActivity(), textView);
        badgeView.setBadgeMargin(0, 10);
        badgeView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
        badgeView.setBadgeBackgroundColor(JfResourceUtil.getSkinColor(R.color.chat_badge_color));
        badgeView.setText("");
        badgeView.setTextSize(7);
        //处理最新新闻栏的角标是否显示  为1时显示   为0时隐藏
        if(EnvironmentVariable.getProperty("news_new_message_notify","0").equals("1")){
            badgeView.show();
        }else {
            badgeView.hide();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveBadgeEvent(UpdateBadgeViewEvent event) {
        //处理最新新闻栏的角标是否显示  为1时显示   为0时隐藏
        if(event!=null&&Integer.valueOf(event.getUserID()) == BadgeUtil.CHAT_ID_NEWS){
            if(badgeView!=null){
                if(EnvironmentVariable.getProperty("news_new_message_notify","0").equals("1")){
                    badgeView.show();
                }else {
                    badgeView.hide();
                }
            }

        }
    }
}
